import router from './router/'
import store from './store'
import Store from '@/store/'
import {getStore, setStore} from '@/utils/store'
import {validatenull} from '@/utils/validate'
import {getToken} from '@/utils/auth'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import website from '@/config/website'
// import {formatPath} from './router/avue-router.js'

NProgress.configure({showSpinner: false});

const lockPage = website.lockPage;  //锁屏页


router.beforeEach(async (to, from, next) => {
    // NProgress.start()
    // 获取已注册的路由配置
    // formatPath(router, Store.getters.menuAll);
    // console.log('已注册路由：' + JSON.stringify(router.getRoutes()));
    console.log('route: ', to);
    // 是否加载左菜单
    const meta = to.meta || {};
    const isMenu = meta.menu === undefined ? to.query.menu : meta.menu;
    store.commit('SET_IS_MENU', isMenu === undefined);

    // 获取 路由地址
    const path = to.path;
    // 获取 路由名称
    const name = to.query.name || to.name;
    // 是否新窗口打开
    if (meta.target) {
        window.open(to.query.url.replace(/#/g, "&"))
        return
    }
    // 是否添加到 Tab
    if (!meta.target && meta.isTab !== false && !validatenull(name) && !validatenull(name)) {
        store.commit('ADD_TAG', {
            fullPath: path,
            path: path,
            name: name,
            params: to.params,
            query: to.query,
            meta: to.meta
        });
    }

    /* 判断是否登录 */
    if (getToken()) {
        if (store.getters.isLock && to.path !== lockPage) {
            // 如果系统激活锁屏，全部跳转到锁屏页
            next({path: lockPage})

        } else {
            let userinfo = getStore({name: "userInfo"});
            if (userinfo != null && userinfo.id != null) {
                // 有当前登录用户信息, 放入 vuex 中
                store.commit('SET_USERIFNO', userinfo);
                // next()
                next()
            } else {
                // 无当前登录用户信息
                await store.dispatch('GetUserInfo');
                next()
            }
        }
    } else {
        // 判断是否需要登录认证, 需要登录认证没有登录访问去登录页, 不需要正常跳转即可
        if (meta.isAuth === false) {
            next()
        } else {
            next('/login')
            // NProgress.done()
        }
    }
})

router.afterEach(to => {
    // NProgress.done();
    // 设置浏览器标题
    document.title = to.name
});